<?php
/**
 * Created by PhpStorm.
 * User: zjx
 * Date: 2016/11/25
 * Time: 10:32
 */

namespace App\Services\Utils;
use App\Exceptions\ApiAbstractException;
use App\Exceptions\ApiErrCode;
use App\Exceptions\ApiException;
use Illuminate\Support\Facades\DB;

class Transaction
{
    /**
     * @test
     *
     * @param callable $db_processor
     * @param bool $throw_err
     * @param mixed $err_res
     *
     * @return mixed
     * @throws \Exception
     */
    public static function handle(callable $db_processor, bool $throw_err = true, $err_res = false)
    {
        try{
            $result = DB::transaction($db_processor);
        } catch (\Exception $e) {
            if ($throw_err) {
                throw new ApiException(
                    ApiErrCode::DB_TRANSACTION_FAILED,
                    $e->getMessage(). "|" . $e->getFile() .":". $e->getLine(),
                    config('app.debug')
                );
            }

            $result = $err_res;
        }

        return $result;
    }
}